#include "fuStringCommand.h"
#include "fuStringHelper.h"
#include "BoostForeach.h"

BEGIN_NAMESPACE_CPPX

fuStringCommand::~fuStringCommand( void )
{

}

cppx::fuStringCommand::fuStringCommand( void )
: m_parai(0),m_quote(false)
{
}

fuStringCommand::fuStringCommand( std::string const & v )
{
    m_quote = true;
    m_text = v;
    InitPara(v);
}

fuStringCommand::fuStringCommand( const char * v )
{
    m_quote = true;
    m_text = v;
    InitPara(v);
}

void fuStringCommand::operator=( std::string const & v )
{
    m_text = v;
    InitPara(v);
}

void fuStringCommand::operator=( const char * v )
{
    m_text = v;
    InitPara(v);
}

void fuStringCommand::InitPara( std::string const &v )
{
    m_parai = 0;
    m_paras.clear();
    for( uint pos = 0; pos < v.length(); pos++ ){
        if( v.at(pos) == '?'){
            m_paras.push_back(para_t(pos));
        }
    }
}

fuStringCommand & fuStringCommand::operator<<( cstr cond )
{
    (*this) << std::string(cond);
    return (*this);
}

fuStringCommand & fuStringCommand::operator<<( std::string cond )
{
    if( m_parai < m_paras.size() ){
        fuStringHelper str_cond(cond);
        if( m_quote && 
            !(str_cond.StartsWith("'") && str_cond.EndsWith("'")) &&
            !(str_cond.Equals("NULL")) )
        {
            str_cond.value().insert(0,"'");
            str_cond.value().append("'");
        }
        m_paras[m_parai++].val = str_cond.value();
    }
    return *this;
}

std::string
fuStringCommand::str(void)
{
    m_text_sql = m_text;
    foreach_r(para_t & para,m_paras){
        m_text_sql.replace(para.pos,1,m_quote && para.val.empty() ? "''" : para.val);
    }
    return m_text_sql;
}

fuStringCommand::operator std::string( void )
{
    return str();
}

END_NAMESPACE_CPPX
